package com.example.moblie;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.moblie.poll.*;
import com.google.android.gms.common.ConnectionResult;

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AbstractNavDrawerActivity {
	
	private NavDrawerActivityConfiguration navDrawerActivityConfiguration;
	// Calculate the shake
		/* Here we store the current values of acceleration, one for each axis */
		private float xAccel;
		private float yAccel;
		private float zAccel;

		/* And here the previous ones */
		private float xPreviousAccel;
		private float yPreviousAccel;
		private float zPreviousAccel;

		/* Used to suppress the first shaking */
		private boolean firstUpdate = true;

		/* What acceleration difference would we assume as a rapid movement? */
		private final float shakeThreshold = 15.0f;

		/* Has a shaking motion been started (one direction) */
		private boolean shakeInitiated = false;

		// location variables
		private SensorManager mySensor;
		private TextView tvDum1;
		private TextView tvDum2;
		private ConnectionResult connectionResult;
		private SharedPreferences mPrefs;
		private Editor mEditor;
		private Location dum1;
		private Location dum2;

		// Search Navigation Drawer
		private ArrayList<Poll> searchedPolls;
		private DrawerLayout mDrawerLayout;
		private ActionBarDrawerToggle mDrawerToggle;
		private CharSequence mDrawerTitle;
		private CharSequence mTitle;
		private RelativeLayout mDrawerRelative;
		
		//test right navigation drawer with GROUP function
		private RelativeLayout mDrawerRight;
		private String rightLI[] = new String[]{"Group"};

		// Search Widgets
		private EditText etSearch;
		private Spinner spnSearchBy;
		private Button btnSearch;
		private String searchBy;
		private static final String[] ARRAY_SEARCHBY = new String[] { "Title",
				"User" };

		// A custom sensor
		private final SensorEventListener mySensorEventListener = new SensorEventListener() {

			@Override
			public void onSensorChanged(SensorEvent event) {
				// TODO Auto-generated method stub
				
				updateAccelParameters(event.values[0], event.values[1],
						event.values[2]); // (1)
				if ((!shakeInitiated) && isAccelerationChanged()) { // (2)
					shakeInitiated = true;
				} else if ((shakeInitiated) && isAccelerationChanged()) { // (3)
					executeShakeAction();
				} else if ((shakeInitiated) && (!isAccelerationChanged())) { // (4)
					shakeInitiated = false;
				}
				
			}

			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub

			}

		};

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Config.context = this;

        if ( savedInstanceState == null ) {
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new view_poll()).commit();
        }
        onCreateMap();
    }
    
    
    public void onCreateMap(){


		//initialize test right drawer
    	/*    	
		mDrawerRight = (RelativeLayout)findViewById(R.id.right_drawer);

		// initialize navigation drawer
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerRelative = (RelativeLayout) findViewById(R.id.left_drawer);
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_launcher, R.string.drawer_open,
				R.string.drawer_close) {

			// Called when a drawer has settled in a completely closed state.
			public void onDrawerClosed(View view) {
				// super.onDrawerClosed(view);
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			// Called when a drawer has settled in a completely open state. 
			public void onDrawerOpened(View drawerView) {
				// super.onDrawerOpened(drawerView);
				
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		// Set the drawer toggle as the DrawerListener
		//mDrawerLayout.setDrawerListener(mDrawerToggle);
		//getActionBar().setDisplayHomeAsUpEnabled(true);
		//getActionBar().setHomeButtonEnabled(true);
		// mDrawerLayout.closeDrawer(mDrawerLinear);
    	/*
		mRightList = (ListView) findViewById(R.id.left_drawer_child);
*/
		// Set the adapter for the search list view



		// Set the search list's click listener
		

		etSearch = (EditText) findViewById(R.id.etSearch);
		spnSearchBy = (Spinner) findViewById(R.id.spnSearchBy);
		btnSearch = (Button) findViewById(R.id.btnSearch);

		etSearch.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					getSearchedPollsFromServer();
					return true;
				}
				return false;
			}
		});

		ArrayAdapter<String> searchAdapter = new ArrayAdapter<String>(this,
				R.layout.spinner_style, MainActivity.ARRAY_SEARCHBY);
		searchAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnSearchBy.setAdapter(searchAdapter);
		spnSearchBy.setSelection(0);
		searchBy = MainActivity.ARRAY_SEARCHBY[0];
		spnSearchBy.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				searchBy = MainActivity.ARRAY_SEARCHBY[position];
				if(position == 1)
					searchBy = "username";
				// Log.d("TEST", searchBy);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		//tvDum1 = (TextView) findViewById(R.id.tvDum1);
		//tvDum2 = (TextView) findViewById(R.id.tvDum2);

		mySensor = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mySensor.registerListener(mySensorEventListener,
				mySensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);

		dum1 = new Location("Dummy1");
		dum2 = new Location("Dummy2");
		dum1.setLatitude(22.3164953);
		dum1.setLongitude(114.1823411);
		dum2.setLatitude(22.3180658);
		dum2.setLongitude(114.1706339);

    }
    
    
    @Override
    protected NavDrawerActivityConfiguration getNavDrawerConfiguration() {
        
        NavDrawerItem[] menu = new NavDrawerItem[] {
                NavMenuSection.create( 100, "Poll"),
                NavMenuItem.create(101,"Poll!", "star_64", false, this),
                NavMenuItem.create(102,"Create Poll", "arrow_64", false, this),
                NavMenuItem.create(103, "My Poll", "polltopic_64", true, this),
                NavMenuItem.create(104, "My Comment", "comments_64", true, this),
                NavMenuItem.create(105, "Search", "search_64", true, this),
                NavMenuSection.create(200, "Account"),
                NavMenuItem.create(201, "Login", "login_xl", false, this),
                NavMenuItem.create(202, "Group", "group_64", false, this)
        };

        
        navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
        navDrawerActivityConfiguration.setMainLayout(R.layout.main);
        navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
        navDrawerActivityConfiguration.setLeftDrawerId(R.id.left_drawer);
        navDrawerActivityConfiguration.setNavItems(menu);

        navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow);       
        navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open);
        navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close);
        navDrawerActivityConfiguration.setBaseAdapter(
            new NavDrawerAdapter(this, R.layout.navdrawer_item, menu ));
        
		searchedPolls = new ArrayList<Poll>();	
        sla = new SearchListAdapter(this, R.layout.search_listview, searchedPolls);


        
        //navDrawerActivityConfiguration.setSearchListAdapter(sla);
        return navDrawerActivityConfiguration;
    }
    
    @Override
    protected void onNavItemSelected(int id) {
        switch ((int)id) {
        case 101:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new view_poll()).commit();
            break;
        case 102:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new create_poll()).commit();
            break;
        case 103:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment()).commit();
            break;
        case 104:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment()).commit();
            break;
        case 105:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment()).commit();
            break;
        case 201:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Login()).commit();
            break;
        case 202:
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new Fragment()).commit();
            break;
        }
    }

	/*
	// Called whenever we call invalidateOptionsMenu()
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(Gravity.LEFT);
		// menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}


    
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
//		if (id == R.id.action_settings) {
//			return true;
//		}
		if(id == R.id.action_right){
			if(!mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
				if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
					mDrawerLayout.closeDrawer(Gravity.LEFT);
				}
                mDrawerLayout.openDrawer(Gravity.RIGHT);
			}else{
                mDrawerLayout.closeDrawer(Gravity.RIGHT);
			}

            return true;
		}
	

		// Pass the event to ActionBarDrawerToggle, if it returns
		// true, then it has handled the app icon touch event
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			if(mDrawerLayout.isDrawerOpen(Gravity.RIGHT)){
				mDrawerLayout.closeDrawer(Gravity.RIGHT);
			}
			return true;
		}
		// Handle your other action bar items...

		return super.onOptionsItemSelected(item);
	}
*/
	private class SearchTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://myfyp.no-ip.org/cs4295/search_polls.php");
			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				String keywords = etSearch.getText().toString();
				if (keywords == null || keywords.equals("")) {
					keywords = "ALL.RECORDS.";
				}
				nameValuePairs
						.add(new BasicNameValuePair("searchBy", searchBy));
				nameValuePairs
						.add(new BasicNameValuePair("keywords", keywords));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				// HttpResponse response = httpclient.execute(httppost);

				// Execute HTTP Post Request
				ResponseHandler<String> responseHandler = new BasicResponseHandler();
				String responseBody = httpclient.execute(httppost,
						responseHandler);
				Log.d("response", responseBody);
				return responseBody;
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				return e.getMessage();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				return e.getMessage();
			}
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(String result) {
			// parse json
			JSONObject json;
			try {
				json = new JSONObject(result);
				JSONArray listArray = json.getJSONArray("list");
				//Log.d("LEN",String.valueOf(listArray.length()));
				searchedPolls.clear();
				for (int i = 0; i < listArray.length(); i++) {
					JSONObject obj;
					obj = listArray.getJSONObject(i);
					int groupid = -1;
					String img = "null";
					
					if(obj.isNull("groupid") ){
						groupid = -1;
					}else{
						groupid = obj.getInt("groupid");
					}
					
					if(obj.isNull("img") ){
						img = "null";
					}else{
						img = obj.getString("img");
					}
					
					Poll p = new Poll(obj.getInt("id"), obj.getInt("userid"),
							obj.getString("username"), obj.getString("title"),
							obj.getString("createdate"), groupid,
							obj.getDouble("latitude"),
							obj.getDouble("longitude"), img);
					searchedPolls.add(p);
				}
				//Log.d("size",String.valueOf(searchedPolls.size()));
				mRightList.invalidateViews();
				//Log.d("size",String.valueOf(searchedPolls.size()));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	public void goSearch(View v){
		SearchTask st = new SearchTask();
		st.execute();
	}

	public void getSearchedPollsFromServer() {
		SearchTask st = new SearchTask();
		st.execute();

	}
	
	public void viewMapWithSearchResult(View v){
		Intent map = new Intent(this, MapView.class);
		if(searchedPolls.isEmpty()){
			goMap(v);
		}else{
			map.putExtra("Filter", searchedPolls);
			startActivity(map);
		}
	}

	public void goMap(View v) {
		Intent map = new Intent(this, MapView.class);
		double[] lats = new double[2];
		double[] longs = new double[2];
		lats[0] = dum1.getLatitude();
		lats[1] = dum2.getLatitude();
		longs[0] = dum1.getLongitude();
		longs[1] = dum2.getLongitude();

		// new, pass using object
		ArrayList<Poll> listOfPoll = new ArrayList<Poll>();

		// for test
		for (int i = 0; i < lats.length; i++) {
			Poll temp = new Poll();
			temp.setLatitude(lats[i]);
			temp.setLongitude(longs[i]);
			listOfPoll.add(temp);
		}
		map.putExtra("pollList", listOfPoll);
		startActivity(map);

	}

	// Store the acceleration values given by the sensor 
	private void updateAccelParameters(float xNewAccel, float yNewAccel,
			float zNewAccel) {
		
		 //we have to suppress the first change of acceleration, it results from
		 //first values being initialized with 0
		 
		if (firstUpdate) {
			xPreviousAccel = xNewAccel;
			yPreviousAccel = yNewAccel;
			zPreviousAccel = zNewAccel;
			firstUpdate = false;
		} else {
			xPreviousAccel = xAccel;
			yPreviousAccel = yAccel;
			zPreviousAccel = zAccel;
		}
		xAccel = xNewAccel;
		yAccel = yNewAccel;
		zAccel = zNewAccel;
	}

	
	
	
	 //If the values of acceleration have changed on at least two axises, we are
	 //probably in a shake motion

	private boolean isAccelerationChanged() {
		float deltaX = Math.abs(xPreviousAccel - xAccel);
		float deltaY = Math.abs(yPreviousAccel - yAccel);
		float deltaZ = Math.abs(zPreviousAccel - zAccel);
		return (deltaX > shakeThreshold && deltaY > shakeThreshold)
				|| (deltaX > shakeThreshold && deltaZ > shakeThreshold)
				|| (deltaY > shakeThreshold && deltaZ > shakeThreshold);
	}

	private void executeShakeAction() {
		if(mDrawerLayout.isDrawerOpen(Gravity.LEFT))
			System.out.print("aa");
			//goMap(findViewById(R.id.btnMap));
	}
    
    
    
    
/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate the menu items for use in the action bar
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main, menu);
	    return super.onCreateOptionsMenu(menu);
	}
	*/
    
	
	
	
	/**

	
	private NavigationDrawerFragment mNavigationDrawerFragment;


	private CharSequence mTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mTitle = getTitle();

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));
	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager
				.beginTransaction()
				.replace(R.id.container,
						PlaceholderFragment.newInstance(position + 1)).commit();
	}

	public void onSectionAttached(int number) {
		switch (number) {
		case 1:
			mTitle = getString(R.string.title_section1);
			break;
		case 2:
			mTitle = getString(R.string.title_section2);
			break;
		case 3:
			mTitle = getString(R.string.title_section3);
			break;
		case 4:
			mTitle = getString(R.string.title_section3);
			break;
		}
	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main, menu);
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


	public static class PlaceholderFragment extends Fragment {

		private static final String ARG_SECTION_NUMBER = "section_number";


		public static PlaceholderFragment newInstance(int sectionNumber) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			return fragment;
		}

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			TextView textView = (TextView) rootView
					.findViewById(R.id.section_label);
			textView.setText(Integer.toString(getArguments().getInt(
					ARG_SECTION_NUMBER)));
			return rootView;
		}

		@Override
		public void onAttach(Activity activity) {
			super.onAttach(activity);
			((MainActivity) activity).onSectionAttached(getArguments().getInt(
					ARG_SECTION_NUMBER));
		}
	}
*/
}
